﻿using System;
using System.Globalization;
using System.Linq;
using Grundy.Administration.Web.Services;
using Grundy.Common;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Administration.Web.Models
{
    public class NewLicenseEntitlementViewModel
    {
        public string Customer { get; set; }
        public string Product { get; set; }
        public string License { get; set; }
        public string Node { get; set; }
        public string ValidFrom { get; set; }
        public string ValidTo { get; set; }

        public virtual Tuple<bool, string, LicenseEntitlement> ToLicenseEntitlement(ProductService ps, LicenseService ls, NodeService ns)
        {   
            var product = ps.GetProduct(Product);
            if(product == null)
                return Tuple.Create(false, "Cannot find a product with name {0}.".FormatWith(Product), (LicenseEntitlement)null);
            var license = ls.GetLicense(License);
            if (license == null)
                return Tuple.Create(false, "Cannot find a license with name {0}.".FormatWith(License), (LicenseEntitlement)null);
            Guid nodeId;
            Guid.TryParse(Node.Split(new[] {',', ' '}).First(), out nodeId);
            var node = ns.GetNodes().FirstOrDefault(i => i.Id == nodeId);
            if (node == null)
                return Tuple.Create(false, "Cannot find a node with id {0}.".FormatWith(Node), (LicenseEntitlement)null);

            DateTime? validFrom = null;
            DateTime? validTo = null;
            DateTime tmp;

            if (!ValidFrom.IsNullOrEmpty() && DateTime.TryParseExact(ValidFrom, "dd/MMMM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out tmp))
                validFrom = tmp;
            if (!ValidTo.IsNullOrEmpty() && DateTime.TryParseExact(ValidTo, "dd/MMMM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out tmp))
                validTo = tmp;

            if(validFrom.HasValue && validTo.HasValue && validFrom <= validTo)
                return Tuple.Create(false, "Valid to date cannot be before valid from date.", (LicenseEntitlement)null);
           
            if(validTo.HasValue && validTo <= Clock.Instance.Utc)
                return Tuple.Create(false, "Valid to date must be after today's date.", (LicenseEntitlement)null);

            return Tuple.Create(true, string.Empty, new LicenseEntitlement{CreatedOn = Clock.Instance.Utc, License = license, Node = node, Product = product, ValidFrom = validFrom, ValidTo = validTo});
        }
    }
}